package com.yimi.yinhepda.views.kua_yue_spotGoods

import android.app.Dialog
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.widget.Button
import android.widget.LinearLayout
import com.pda.uce.commom.util.MyDialog
import com.pda.ym.db.table.UnloadScanTable
import com.yimi.yinhepda.R
import com.yimi.yinhepda.adapter.RecycleAdapter.KuaYueDifferChildWaybillAdapter
import com.yimi.yinhepda.adapter.RecycleAdapter.KuaYueDifferReportAdapter
import com.pda.ym.base.CommonViewHolder
import com.pda.ym.base.BaseTitleActivity
import com.pda.ym.callbacks.UICallBack
import com.yimi.yinhepda.db.dao.UnloadScanTableDao
import com.yimi.yinhepda.entity.bean.KuaYueChildWaybillEntitiy
import com.yimi.yinhepda.entity.bean.KuaYueTaskDetailEntity
import com.yimi.yinhepda.entity.bean.KuaYueTaskEntity
import com.yimi.yinhepda.entity.request.KuaYueFinshRequest
import com.yimi.yinhepda.entity.response.ZiTiScanUploadResponse
import com.pda.ym.net.NetRequest
import com.pda.ym.utils.ActivityStack
import com.pda.ym.utils.Constants
import com.pda.ym.utils.SoundVibratorManager
import com.yimi.yinhepda.utils.*
import kotlinx.android.synthetic.main.activity_kuayue_differ_report.*

/**
 * @author: lj
 * Date: 2020/4/18 17:48
 * Description:跨越差异报告界面
 */
class KuaYueDifferReportActivity : BaseTitleActivity(), CommonViewHolder.onItemCommonClickListener {

    //跨越任务实体
    private var mTaskEntity: KuaYueTaskEntity? = null
    //操作类型，操作码:1 -装车，2- 卸车
    private val operTypeCode = 2

    override fun getPageName(): String {
        return "跨越差异报告界面"
    }

    override fun setContentViewId(): Int {
        return R.layout.activity_kuayue_differ_report
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        iv_back.setOnClickListener(this)
        iv_submit.setOnClickListener(this)

        mTaskEntity = intent.getSerializableExtra(Common.KUAYUE_TASK_KEY) as KuaYueTaskEntity

        tv_taskNo.text = "任务号：${mTaskEntity!!.taskNo}"
        tv_carNo.text = "车牌号：${mTaskEntity!!.carNo}"
        val piaoNum = intent.getStringExtra("piaoNum")
        val jianNum = intent.getStringExtra("jianNum")
        val sPiaoNum = intent.getStringExtra("sPiaoNum")
        val sJianNum = intent.getStringExtra("sJianNum")
        tv_jiao_jie_num.text = "交接票/件：${piaoNum}/${jianNum}"
        tv_real_operation_num.text = "实操票/件：${sPiaoNum}/${sJianNum}"

        //统计多货票件，少货票件
        var morePiao = 0
        var moreJian = 0
        var lessPiao = 0
        var lessJian = 0
        val execptionList = mutableListOf<KuaYueTaskDetailEntity>()
        KuaYueSpotGoodsActivity.mDataList.forEach { detail ->
            if (detail.moreGoods > 0 || detail.lessGoods > 0) {
                if (detail.moreGoods > 0) {
                    morePiao++
                    moreJian += detail.moreGoods
                }
                if (detail.lessGoods > 0) {
                    lessPiao++
                    lessJian += detail.lessGoods
                }
                execptionList.add(detail)
            }
        }

        tv_more_goods.text = "多货：${morePiao}票${moreJian}件"
        tv_less_goods.text = "少货：${lessPiao}票${lessJian}件"

        if (execptionList.isNullOrEmpty()) {
            tv_noDifferData.visibility = View.VISIBLE
            rv_list.visibility = View.INVISIBLE
        } else {
            tv_noDifferData.visibility = View.GONE
            val adapter = KuaYueDifferReportAdapter(this, execptionList, this)
            rv_list.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
            rv_list.adapter = adapter
        }
    }

    override fun showBack(): Boolean {
        return true
    }

    override fun setBack() {
        finish()
    }

    override fun setTitle(): String {
        return "差异报告"
    }

    override fun onClick(v: View?) {
        super.onClick(v)
        when (v?.id) {
            R.id.iv_back -> finish()
            R.id.iv_submit -> {
                //提交
                MyDialog.showAlertDialog(this, "确定提交？", "确定", "取消",
                        { dialog, _ ->
                            dialog.dismiss()
                            //数据提交
                            submitData()
                        }, { dialog, _ -> dialog.dismiss() })
            }
        }
    }

    override fun onItemClickListener(position: Int) {
        //点击查看子单的多货和少货
        showChildWaybillDialog(KuaYueSpotGoodsActivity.mDataList[position])
    }

    override fun onItemLongClickListener(position: Int) {
    }

    /**
     * 显示异常子单信息
     */
    private fun showChildWaybillDialog(data: KuaYueTaskDetailEntity?) {
        val layout = LayoutInflater.from(this).inflate(R.layout.alert_dialog_kuayue_exception_child_waybill, null) as LinearLayout
        //司机姓名
        val rvList = layout.findViewById<RecyclerView>(R.id.rv_list)
        val btnOk = layout.findViewById<Button>(R.id.btn_ok)
        val dialog = Dialog(this, R.style.AsyncTaskDialog)
        dialog.addContentView(layout, LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT))
        dialog.window.setBackgroundDrawableResource(android.R.color.transparent)
        dialog.window.decorView.setPadding(10, 0, 10, 0)
        dialog.setCanceledOnTouchOutside(false)
        dialog.show()

        //过滤出少货和多货运单
        val list = mutableListOf<KuaYueChildWaybillEntitiy>()
        data?.childNos?.forEach { child ->
            if (child.exceptionType != "") {
                list.add(child)
            }
        }

        val adapter = KuaYueDifferChildWaybillAdapter(this, list)
        rvList.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        rvList.adapter = adapter

        btnOk.setOnClickListener {
            dialog.dismiss()
        }
    }

    /**
     * 提交数据
     */
    private fun submitData() {
        val scanTableDao = UnloadScanTableDao()
        val request = KuaYueFinshRequest()
        request.taskNo = mTaskEntity!!.taskNo
        request.deptCode = sharedPreferUtil.deptCode
        request.carNo = mTaskEntity!!.carNo
        request.driverNo = mTaskEntity!!.driverNo
        request.driverName = mTaskEntity!!.driverName
        request.driverPhone = mTaskEntity!!.driverPhone
        //组装本地扫描数据
        val scanedData = scanTableDao.queryKuaYueScanedData(mTaskEntity?.taskNo, operTypeCode)
        if (scanedData.isNullOrEmpty()) {
            showToast("无扫描运单，不可提交！")
            SoundVibratorManager.playSound(2)
            return
        }
        //组装提交数据
        request.records = getScanData(scanedData)
        showPgDlg("任务提交中...")
        NetRequest().setMethod(NetRequest.Method.POST_STRING)
                .setResponsClazz(ZiTiScanUploadResponse::class.java)
                .setUrl(Constants.URL_QUERY_KUAYUN_FINISH_TASK)
                .setRequestObject(request)
                .execute(object : UICallBack() {
                    override fun onSuccess(obj: Any?) {
                        dismissPgDlg()
                        //扫描数据更新为已上传状态
                        scanedData.forEach {
                            it.isUpload = 1
                            scanTableDao.update(it)
                        }
                        finish()
                        ActivityStack.getInstance().activities.forEach {
                            if (it is KuaYueSpotGoodsActivity) {
                                it.finish()
                            }
                        }
                        showToast("提交成功！")
                        SoundVibratorManager.playSound(1)
                    }

                    override fun onError(msg: String?) {
                        dismissPgDlg()
                        showToast(msg)
                    }
                })
    }

    /**
     * 组装提交数据
     */
    private fun getScanData(scanedData: MutableList<UnloadScanTable>): MutableList<KuaYueTaskDetailEntity> {
        val list = mutableListOf<KuaYueTaskDetailEntity>()
        scanedData.forEach { local ->
            val uploadEntity = KuaYueTaskDetailEntity()
            uploadEntity.taskNo = local.task
            uploadEntity.deptCode = local.deptCode
            uploadEntity.goodsName = local.goodsName
            uploadEntity.waybillNo = local.waybillNo
            uploadEntity.subWaybillNo = local.childWaybillNo
            uploadEntity.outsideNo = local.kuayueWaybillNo
            uploadEntity.subOutsideNo = local.kuayueChildWaybillNo
            uploadEntity.volume = local.volume.toDouble()
            uploadEntity.weight = local.weight.toDouble()
            uploadEntity.chargedWeight = local.chargedWeight.toDouble()
            uploadEntity.pieceNum = local.pieceNum
            uploadEntity.operTypeCode = local.operTypeCode
            uploadEntity.operEmpName = local.operEmpName
            uploadEntity.operEmpCode = local.operEmpCode
            uploadEntity.scanTime = local.scanTime
            uploadEntity.operPersonCodes = local.operPersonCodes
            uploadEntity.operPersonNames = local.operPersonNames
            uploadEntity.areaCode = local.areaCode
            uploadEntity.nextDeptCode = local.nextDeptCode
            uploadEntity.nextDeptName = local.nextDeptName
            uploadEntity.inputType = local.inputType
            list.add(uploadEntity)
        }
        return list
    }
}